define(['ionic'], function () {

    angular.module('ShipPicking', ['ionic'])
        .run(function () {
            u9.hideLoading();
        })
    /******路由配置******/
        .config(['$stateProvider', '$urlRouterProvider', '$ionicConfigProvider', function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
            $stateProvider
                .state('picks', {
                    url: '/picks',
                    templateUrl: 'tpls/picks.html',
                    controller: 'PicksCtrl'
                })
                .state('pick', {
                    url: '/picks/:docId?docNo',
                    templateUrl: 'tpls/pick.html',
                    controller: 'ShipLinesCtrl'
                });
            $urlRouterProvider.otherwise('/picks');

            $ionicConfigProvider.platform.android.navBar.alignTitle('center');
            $ionicConfigProvider.platform.android.backButton.previousTitleText(false);
            $ionicConfigProvider.platform.android.navBar.transition('view');
            $ionicConfigProvider.platform.android.views.transition('ios');
            $ionicConfigProvider.platform.android.views.swipeBackEnabled(true);
            $ionicConfigProvider.platform.android.views.swipeBackHitWidth(45);
            $ionicConfigProvider.platform.android.tabs.style('standard');
            $ionicConfigProvider.platform.android.tabs.position('bottom');
            $ionicConfigProvider.platform.android.form.toggle('large');

            $ionicConfigProvider.platform.default.backButton.previousTitleText(false);
            $ionicConfigProvider.platform.default.backButton.text(false);

            $ionicConfigProvider.views.maxCache(0);
        }])

    /******过滤器******/
        .filter('PicksQuery', function () {
            return function (picks, queryStr) {
                if (queryStr === '') {
                    return picks;
                }
                var aPicks = [];
                angular.forEach(picks, function (pick) {
                    if(pick.DocNO.toUpperCase().indexOf(queryStr.toUpperCase()) > -1 ||
                       pick.Customer_Name.toUpperCase().indexOf(queryStr.toUpperCase()) > -1
                    ) {
                        aPicks.push(pick);
                    }
                });
                return aPicks;
            };
        })

    /******指令******/
        .directive('getFocus', ['$timeout', function($timeout) {
            return {
                scope: {
                    trigger: '@getFocus'
                },
                link: function(scope, element) {
                    scope.$watch('trigger', function(newValue, oldValue) {
                        if (newValue === 'false') {
                            return;
                        }
                        var delay = 0;
                        if (newValue === oldValue) {
                            delay = 400;
                        }
                        $timeout(function() {
                            element[0].focus();
                        }, delay);
                    });
                }
            }
        }])

    /******服务******/
        .constant('SHIPPICKCONSTANTS', {
            GetShipLineInfoCmd: 'UFIDA.U9.ISV.SM.IGetShipLineInfo',
            OnLineCheckCmd: 'UFIDA.U9.ISV.SM.IOnLineCheck',
            OnShipConformCmd: 'UFIDA.U9.ISV.SM.IShipConformISV',
            NumPerPage: 10
        })

        .factory('cordovaBarcodeScanner', ['$q', function ($q) {
            return {
                scan: function (config) {
                    var q = $q.defer();
                    u9.plugins.barcodeScanner.scan(function (result) {
                        q.resolve(result);
                    }, function (err) {
                        q.reject(err);
                    }, config);
                    return q.promise;
                },
                encode: function (type, data) {
                    var q = $q.defer();
                    type = type || "TEXT_TYPE";
                    u9.plugins.barcodeScanner.encode(type, data, function (result) {
                        q.resolve(result);
                    }, function (err) {
                        q.reject(err);
                    });
                    return q.promise;
                }
            };
        }])

        .factory('ShipPickService', ['$q', 'SHIPPICKCONSTANTS', function ($q, SHIPPICKCONSTANTS) {
            var o = {},
                shipLines = [];

            o.getShipLineInfo = function (shipId) {
                var defer = $q.defer();

                u9.callSV({
                    name: SHIPPICKCONSTANTS.GetShipLineInfoCmd,
                    params: [shipId],
                    onSuccess: function (data) {
                        shipLines = data;
                        defer.resolve(data);
                    },
                    onFailure: function (err) {
                        defer.reject(err);
                    }
                });

                return defer.promise;
            };

            o.onLineCheck = function (barCodes, shipId) {
                var defer = $q.defer();

                u9.callSVAlone({
                    name: SHIPPICKCONSTANTS.OnLineCheckCmd,
                    params: [barCodes, shipId],
                    onSuccess: function (data) {
                        defer.resolve(data);
                    },
                    onFailure: function (err) {
                        defer.reject(err);
                    }
                });

                return defer.promise;
            };

            o.onShipConform = function (shipId) {
                var defer = $q.defer();

                u9.callSV({
                    name: SHIPPICKCONSTANTS.OnShipConformCmd,
                    params: [shipId],
                    onSuccess: function (data) {
                        defer.resolve(data);
                    },
                    onFailure: function (err) {
                        defer.reject(err);
                    }
                });

                return defer.promise;
            };

            o.getPicksProfile = function () {
                var picksProfile = [];
                angular.forEach(shipLines, function (shipLine) {
                    picksProfile.push({
                        DocID: shipLine.DocID,
                        DocNO: shipLine.DocNO,
                        DocLineSrcNo: shipLine.DocLineSrcNo,
                        Customer_Name: shipLine.Customer_Name,
                        BusinessPerson_Name: shipLine.BusinessPerson_Name
                    });
                });
                return picksProfile;
            };

            o.getShipLines = function () {
                var tmpShipLines = [];
                angular.forEach(shipLines, function (shipLine) {
                    tmpShipLines.push({
                        DocNO: shipLine.DocNO,
                        Customer_Name: shipLine.Customer_Name,
                        BusinessDate: shipLine.BusinessDate.format('yyyy-MM-dd'),
                        ItemMaster_Name: shipLine.ItemMaster_Name,
                        barCode: shipLine.barCode,
                        LotCode: shipLine.LotCode,
                        Wh_Name: shipLine.Wh_Name,
                        ShipQtyInvAmount: shipLine.ShipQtyInvAmount,
                        UOM_Code: shipLine.UOM_Code
                    });
                });
                return tmpShipLines;
            };

            return o;
        }])

    /******控制器******/
        .controller('PicksCtrl', ['$scope', 'ShipPickService', 'SHIPPICKCONSTANTS',
            function ($scope, ShipPickService, SHIPPICKCONSTANTS) {
                $scope.pickData = {
                    picks: [],
                    query: '',
                    currentNum: 0
                };

                ShipPickService.getShipLineInfo(0).then(function () {
                    $scope.pickData.picks = ShipPickService.getPicksProfile();
                    refreshPicks();
                });

                $scope.doRefresh = function () {
                    refreshPicks();
                    $scope.$broadcast('scroll.refreshComplete');
                };

                function refreshPicks () {
                    if ($scope.pickData.currentNum < $scope.pickData.picks.length) {
                        $scope.pickData.currentNum += SHIPPICKCONSTANTS.NumPerPage;
                    } else {
                        u9.alert('没有新数据');
                        return;
                    }
                }
            }
        ])
        .controller('ShipLinesCtrl', ['$scope', '$timeout', '$stateParams', '$state', 'cordovaBarcodeScanner', 'ShipPickService', 'SHIPPICKCONSTANTS',
            function ($scope, $timeout, $stateParams, $state, cordovaBarcodeScanner, ShipPickService, SHIPPICKCONSTANTS) {
                $scope.shipData = {
                    shipLines: [],
                    title: $stateParams.docNo,
                    barCodes: [],
                    inputCode: '',
                    barCode: true,
                    pickDetail: false,
                    confirmDisabled: true,
                    currentNum: 0,
                    timeOut: null
                };

                $scope.activeBarCode = function () {
                    $scope.shipData.barCode = true;
                    $scope.shipData.pickDetail = false;
                };
                $scope.activePickDetail = function () {
                    $scope.shipData.barCode = false;
                    $scope.shipData.pickDetail = true;
                };

                $scope.refreshBarcode = function () {
                    $timeout.cancel($scope.shipData.timeOut);
                    $scope.shipData.timeOut = $timeout(function () {
                        if ($scope.shipData.inputCode) {
                            $scope.shipData.barCodes.push({
                                code: $scope.shipData.inputCode,
                                error: false
                            });
                            //清除输入框
                            $scope.shipData.inputCode ='';
                        }
                    }, 500);
                };

                $scope.deleteBarcodeByIndex = function (index) {
                    $scope.shipData.barCodes.splice(index,1);
                };

                $scope.checkInline = function () {
                    var tempCodes = [];
                    angular.forEach($scope.shipData.barCodes, function (barCode) {
                        tempCodes.push(barCode.code);
                    });
                    ShipPickService.onLineCheck(tempCodes, $stateParams.docId).then(function (checkShipLines) {
                        var validLines = {},
                            barcodeResult = {},
                            hasValid = false;
                        angular.forEach(checkShipLines, function (checkShipLine) {
                            if (checkShipLine.DocNO) {
                                hasValid = true;
                                validLines[checkShipLine.DocNO] = checkShipLine.BarCode_Code;
                            }
                            barcodeResult[checkShipLine.BarCode_Code] = !!checkShipLine;
                        });

                        angular.forEach($scope.shipData.shipLines, function (shipLine) {
                            if (validLines.hasOwnProperty(shipLine.DocNO)) {
                                $scope.shipData.shipLines[j].barCode = validLines[shipLine.DocNO];
                            }
                        });
                        angular.forEach($scope.shipData.barCodes, function (barCode) {
                            barCode.error = barcodeResult[barCode.code];
                        });

                        $scope.shipData.confirmDisabled = !hasValid;
                        if (hasValid) {
                            $scope.activePickDetail();
                        }
                    }, function (err) {
                        angular.forEach($scope.shipData.barCodes, function (barCode) {
                            barCode.error = true;
                        });
                    });
                };

                $scope.confirmShip = function () {
                    ShipPickService.onShipConform($stateParams.docId).then(function (data) {
                        $scope.shipData.confirmDisabled = true;
                        $state.go('picks');
                    }, function (err) {
                        u9.alert(err._message);
                    });
                };

                ShipPickService.getShipLineInfo($stateParams.docId).then(function () {
                    $scope.shipData.shipLines = ShipPickService.getShipLines();
                    refreshShipLines();
                });

                $scope.doRefresh = function () {
                    if ($scope.shipData.pickDetail) {
                        refreshShipLines();
                    }
                    $scope.$broadcast('scroll.refreshComplete');
                };
                function refreshShipLines () {
                    if ($scope.shipData.currentNum < $scope.shipData.shipLines.length) {
                        $scope.shipData.currentNum += SHIPPICKCONSTANTS.NumPerPage;
                    } else {
                        u9.alert('没有新数据');
                        return;
                    }
                }

                $scope.scanCode = function () {
                    cordovaBarcodeScanner.scan()
                        .then(function (scanResult) {
                            if (scanResult.cancelled) {
                                return;
                            }
                            //if (scanResult.format === 'EAN_13') {
                            $scope.shipData.barCodes.push({
                                code: scanResult.text,
                                error: false
                            });
                        //}
                    });
                };
            }
        ]);
});